/**
 *  @brief SoftI2C
 *  interface to I2C (two-wire) communication.
 */

#include "wirish.h"
#include "gpio.h"

#ifndef _SOFTI2C_H_
#define _SOFTI2C_H_

#define SI2C_SUCCESS		0	/* transmission was successful */
#define SI2C_ENACKADDR	2	/* received nack on transmit of address */
#define SI2C_ENACKTRNS	3	/* received nack on transmit of data */

							
#define SI2C_WRITE 0
#define SI2C_READ  1

static inline void SI2C_DELAY(uint8 delay)
{
	for(uint8 i = 0; i < delay; i++)
		asm volatile("nop");
}

class SoftI2C
{
private:
	gpio_dev *sda_port, *scl_port;
	uint8 sda_pin, scl_pin;

//	uint8 writeOneByte(uint8 address);
//	uint8 readOneByte(uint8 address, uint8 *data);

	void i2c_start(void);
	void i2c_stop(void);
	uint8 i2c_get_ack(void);
	void i2c_send_ack(void);
	void i2c_send_nack(void);
	uint8 i2c_shift_in(void);
	void i2c_shift_out(uint8 val);

public:
	SoftI2C(void);

	uint8 SDA, SCL;
	volatile uint8 Delay;
	uint8 Data;
	uint8 SlaveAddress;

	void begin(uint8 sda, uint8 scl);

	uint8 writeReg(uint8 register_address, uint8 data);
	uint8 writeReg(uint8 slave_address, uint8 register_address, uint8 data);

	uint8 readReg(uint8 register_address);
	uint8 readReg(uint8 register_address, uint8 *data);
	uint8 readReg(uint8 slave_address, uint8 register_address);
	uint8 readReg(uint8 slave_address, uint8 register_address, uint8 *data);
};

#endif // _SoftI2C_H_
